package xworker.gluon.glisten.control;

import com.gluonhq.charm.glisten.control.TextInput;
import javafx.scene.control.TextFormatter;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.javafx.beans.property.PropertyFactory;
import xworker.javafx.control.ControlActions;
import xworker.javafx.util.JavaFXUtils;

import java.util.function.Function;

public class TextInputActions {
    static{
        PropertyFactory.regist(TextInput.class, "floatTextProperty", o -> {
            TextInput obj = (TextInput) o;
            return obj.floatTextProperty();
        });
        PropertyFactory.regist(TextInput.class, "promptTextProperty", o -> {
            TextInput obj = (TextInput) o;
            return obj.promptTextProperty();
        });
        PropertyFactory.regist(TextInput.class, "errorValidatorProperty", o -> {
            TextInput obj = (TextInput) o;
            return obj.errorValidatorProperty();
        });
        PropertyFactory.regist(TextInput.class, "textFormatterProperty", o -> {
            TextInput obj = (TextInput) o;
            return obj.textFormatterProperty();
        });
        PropertyFactory.regist(TextInput.class, "textProperty", o -> {
            TextInput obj = (TextInput) o;
            return obj.textProperty();
        });
    }

    public static void init(TextInput node, Thing thing, ActionContext actionContext){
        ControlActions.init(node, thing, actionContext);

        Function<String, String> errorValidator = JavaFXUtils.getObject(thing, "errorValidator", actionContext);
        if(errorValidator != null){
            node.setErrorValidator(errorValidator);
        }

        if(thing.valueExists("floatText")){
            String floatText = JavaFXUtils.getString(thing, "floatText", actionContext);
            if(floatText != null){
                node.setFloatText(floatText);
            }
        }

        String promptText = JavaFXUtils.getString(thing, "promptText", actionContext);
        if(promptText != null){
            node.setPromptText(promptText);
        }

        TextFormatter<?> textFormatter = JavaFXUtils.getObject(thing, "textFormatter", actionContext);
        if(textFormatter != null){
            node.setTextFormatter(textFormatter);
        }

        String text = JavaFXUtils.getString(thing, "text", actionContext);
        if(text != null){
            node.setText(text);
        }
    }

    public static void createErrorValidator(ActionContext actionContext){
        Thing thing = actionContext.getObject("self");
        TextInput parent = actionContext.getObject("parent");

        parent.setErrorValidator(s -> thing.doAction("applay", actionContext, "value", s));
    }
}
